package com.sjp.blog.controller;

import com.sjp.blog.common.vo.Response;
import com.sjp.blog.entity.Article;
import com.sjp.blog.repository.ArticleRepository;
import com.sjp.blog.utils.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    private ArticleRepository articleRepository;

    @GetMapping("/list")
    public Response list() {
        List<Article> all = articleRepository.findAll();
        return ResponseUtil.success(all);
    }

    @GetMapping("/pageList")
    public Response pageList(@RequestParam(value = "page", defaultValue = "1") Integer page,
                             @RequestParam(value = "size", defaultValue = "20") Integer size) {
        PageRequest pageRequest = PageRequest.of(page - 1, size);
        Example<Article> example = Example.of(new Article());
        Page<Article> resultPage = articleRepository.findAll(example, pageRequest);
        return ResponseUtil.success(resultPage);
    }

    @GetMapping("/{id}")
    public Response detail(@PathVariable("id") Long id) {
        Optional<Article> op = articleRepository.findById(id);
        return ResponseUtil.success(op.orElse(null));
    }

    @DeleteMapping("/{id}")
    public Response delete(@PathVariable("id") Long id) {
        articleRepository.deleteById(id);
        return ResponseUtil.success();
    }

    @PostMapping("")
    public Response add(@RequestBody Article article) {

        article.setCtime(new Date());
        articleRepository.save(article);
        return ResponseUtil.success(article);
    }

    @PutMapping("/{id}")
    public Response add(@PathVariable("id") Long id, @RequestBody Article article) {
        article.setId(id);
        article.setUtime(new Date());
        articleRepository.save(article);
        return ResponseUtil.success(article);
    }
}
